package org.txlcn.demo;

import com.codingapi.txlcn.common.util.Transactions;
import com.codingapi.txlcn.tc.annotation.DTXPropagation;
import com.codingapi.txlcn.tc.annotation.LcnTransaction;
import com.codingapi.txlcn.tc.annotation.TxcTransaction;
import com.codingapi.txlcn.tracing.TracingContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.txlcn.demo.common.db.domain.Order;
import org.txlcn.demo.common.spring.ServiceStockClient;

import java.util.Date;

/**
 * Description:
 * Date: 2018/12/25
 *
 * @author ujued
 */
@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    final OrderMapper orderMapper;
    final ServiceStockClient serviceStockClient;

    public OrderServiceImpl(OrderMapper orderMapper, ServiceStockClient serviceStockClient) {
        this.orderMapper = orderMapper;
        this.serviceStockClient = serviceStockClient;
    }

    @Override
    @LcnTransaction
    public String rpc(String value) {


        Order order = new Order();
        order.setGroupId(TracingContext.tracing().groupId());
        order.setDemoField(value);
        order.setAppName(Transactions.getApplicationId());
        order.setCreateTime(new Date());
        orderMapper.saveOrder(order);

        String stock = serviceStockClient.rpc(value);

        if ("ii".equals(value)) {
            try {
                Thread.sleep(5000);
                throw new RuntimeException("Service B save failed");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        return "ok-service-order ->" + stock;
    }
}
